package main

import (
	"encoding/json"
	"fmt"
	"github.com/nats-io/go-nats"
	"github.com/pborman/uuid"
	"log"
	"time"
)

const (
	//url   = "nats://192.168.3.125:4222"
	NatUrl          = nats.DefaultURL
	ProductInfoSubj = "product_info_subj"
)

var (
	connClient *nats.Conn
	err        error
)

func init() {
	if connClient, err = nats.Connect(NatUrl); err != nil {
		log.Fatal("初始化conn失败：", err)
	}
}

func main() {
	// 推送基础包数据
	SendBaseData()

}

type BaseData struct {
	Name string
	Age  int64
	High int64
}

//client send message to server
func ClientSendMsgToServerByRequest(subj, data string) {
	id := uuid.New()
	log.Println(id)
	repMsg, err := connClient.Request(subj, []byte(id+":"+data), time.Second*1)
	if err != nil {
		log.Print("消息推送失败：", err)
	} else {
		fmt.Println("发送成功回执信息为：", string(repMsg.Data))
		fmt.Println("发送成功回执信息为：", repMsg.Sub)
		fmt.Println("发送成功回执信息为：", repMsg.Reply)
		fmt.Println("发送成功回执信息为：", repMsg.Subject)
	}

}

/*
客户端的推送
./main -port=client -subj=weather -data=hello world
*/
func SendBaseData() {
	subj := ProductInfoSubj
	data := new(BaseData)
	data.Name = "James"
	data.Age = 24
	data.High = 187

	dataStr, err := json.Marshal(data)
	if err != nil {
		log.Fatal("json数据转化成为str：", err)
	}
	ClientSendMsgToServerByRequest(subj, string(dataStr))
}
